package com.thiswhyme.illegalword.core;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @description: 敏感词服务
 * @author: thiswhyme
 * @date: 2021/3/30
 */
public class IllegalWordServiceImpl implements IllegalWordService {

    public static Map<String, String> thesaurus;

    private RedisTemplate redisTemplate;

    public IllegalWordServiceImpl(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 将redis中的敏感词库初始化到内存，并构建成树形结构
     */
    public void initIntoMemory() {
        Set<String> keyWordSet = (Set<String>) redisTemplate.opsForValue().get(Constants.ILLEGAL_THESAURUS_CACHE_KEY);
        thesaurus = new HashMap(keyWordSet.size());

        String key;
        Map nowMap;
        Map<String, String> newWorMap;
        Iterator<String> iterator = keyWordSet.iterator();
        while (iterator.hasNext()) {
            key = iterator.next();
            nowMap = thesaurus;
            for (int i = 0; i < key.length(); i++) {
                char keyChar = key.charAt(i);
                Object wordMap = nowMap.get(keyChar);

                if (wordMap != null) {
                    nowMap = (Map) wordMap;
                } else {
                    newWorMap = new HashMap<>();
                    newWorMap.put(Constants.END_FLAG_NAME, Constants.END_FLAG_VALUE_NOT_END);
                    nowMap.put(keyChar, newWorMap);
                    nowMap = newWorMap;
                }

                if (i == key.length() - 1) {
                    nowMap.put(Constants.END_FLAG_NAME, Constants.END_FLAG_VALUE_END);
                }
            }
        }
    }

    @Override
    public boolean isContainsIllegalWord(String txt, MatchType matchType) {
        return IllegalWordUtils.isContainsIllegalWord(txt, matchType, thesaurus);
    }

    @Override
    public Set<String> getIllegalWords(String txt, MatchType matchType) {
        return IllegalWordUtils.getIllegalWords(txt, matchType, thesaurus);
    }

    @Override
    public String replaceIllegalWords(String txt, MatchType matchType, String replaceChar) {
        return IllegalWordUtils.replaceIllegalWords(txt, matchType, replaceChar, thesaurus);
    }
}
